﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace MigrationTool
{
    public static class RegistryValue
    {
        public static string ConvertRegistryBinaryValueToString(object value)
        {
            string strValue = string.Empty;

            if (value != null)
            {
                byte[] byteValue = (byte[])value;
                strValue = Encoding.Unicode.GetString(byteValue).TrimEnd('\0');
            }

            return strValue;
        }

        private static byte[] ConvertStringToRegistryBinaryValue(string value)
        {
            byte[] byteValue = null;

            if (!string.IsNullOrEmpty(value))
            {
                byteValue = Encoding.Unicode.GetBytes(value + "\0");
            }

            return byteValue;
        }

        /// <summary>
        /// IMAP接続用パスワードを暗号化する
        /// </summary>
        /// <param name="imapUserPassword">パスワード</param>
        /// <returns>暗号化後のパスワード</returns>
        public static byte[] EncryptImapPassword(string imapUserPassword)
        {
            byte[] registryValue = null;

            if (!string.IsNullOrEmpty(imapUserPassword))
            {
                //パスワードを暗号化する
                byte[] imapUserPasswordByte = ConvertStringToRegistryBinaryValue(imapUserPassword + "\0");
                byte[] encryptPassword = ProtectedData.Protect(imapUserPasswordByte, null, DataProtectionScope.LocalMachine);

                //暗号化メカニズムを指定する
                registryValue = new byte[encryptPassword.Length + 2];
                registryValue[0] = byte.Parse("2");
                encryptPassword.CopyTo(registryValue, 1);
            }

            return registryValue;
        }
    }
}
